import Toast from "./toast";

// 当前toast
let currentToast

// 插件
export default {
    install(Vue,options){
        // toast 插件
        Vue.prototype.$toast = (message,propsData) => {
            // 如果当前有toast，则清除
            if(currentToast){
                currentToast.close()
            }
            currentToast = createToast(
                Vue,
                {
                    message, 
                    propsData,
                    onClose:()=>{ 
                        currentToast = null
                    }
                }
            )
        }
    }
}

// 创建toast
function createToast (Vue,{message, propsData, onClose}){
    let Constructor = Vue.extend(Toast)
    let toast = new Constructor({
        propsData
    })
    // 指定插槽值
    toast.$slots.default = [message || 'message']
    // 注册toast 组件
    toast.$mount()
    // 监听toast 销毁
    toast.$on('close',onClose)
    // 插入到body
    document.body.appendChild(toast.$el)
    return toast
}